package oa.struts.action;

import java.io.ByteArrayInputStream;
import java.util.Collection;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;

import oa.domain.system.Privilege;
import oa.domain.system.User;
import oa.service.LoginService;
import oa.service.PrivilegeService;
import oa.struts.action.base.BaseAction;
import oa.util.OAUtils;
import oa.util.SecurityCode;
import oa.util.SecurityImage;

@Controller("loginAction")
@Scope("prototype")
public class LoginAction extends BaseAction<User> implements SessionAware{

	@Resource(name="loginService")
	private LoginService loginService;
	
	@Resource(name="privilegeService")
	private PrivilegeService privilegeService;
	
	private String securityCode;
	

	private Map<String,Object> session;
	//图片流
	private ByteArrayInputStream imageStream;
	
	public ByteArrayInputStream getImageStream() {
		return imageStream;
	}

	public void setImageStream(ByteArrayInputStream imageStream) {
		this.imageStream = imageStream;
	}
    
	public String getSecurityCode() {
		return securityCode;
	}

	public void setSecurityCode(String securityCode) {
		this.securityCode = securityCode;
	}

	public String generateSICode()
    {
    	String securityCode = SecurityCode.getSecurityCode();
        imageStream = SecurityImage.getImageAsInputStream(securityCode);
    	 //放入session中
    	session.put("SESSION_SECURITY_CODE", securityCode);
        return SUCCESS;

    }
	@Override
	public void setSession(Map<String, Object> session) {
		// TODO Auto-generated method stub
		this.session = session;
	}

	public String login(){
		String serverCode = session.get("SESSION_SECURITY_CODE").toString();
		User user = this.loginService.login(this.getModel().getUsername(), this.getModel().getPassword());
		if(user == null){//用户名或者密码不正确
			ActionContext.getContext().put("message", "用户名或者密码错误");
			//this.addActionMessage("用户名或者密码错误");
			return "input";
		}else if(!serverCode.equalsIgnoreCase(securityCode))
		{
			ActionContext.getContext().put("message", "验证码输入错误");
			//this.addActionMessage("验证码输入错误");
			return "input";
		}
		else{
			OAUtils.putUserToSession(user);
			Collection<Privilege> privileges = this.privilegeService.getFunctionsByUid(user.getUid());
			//该用户能够访问到的功能权限放入到了session中
			OAUtils.putFunctionsToSession(privileges);
			return "index";
		}

	}
	
	public String logout()
	{
		//从Session中清除登录用户
	    ServletActionContext.getRequest().getSession().removeAttribute("user");	
	    ServletActionContext.getRequest().getSession().removeAttribute("SESSION_SECURITY_CODE");	
		return "logout";
	}
	
	
	public String show()
	{
		return "show";
	}
}
